package yt.demo.appcoresystem.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import yt.demo.appcommonbean.exception.LogicException;
import yt.demo.appcommondb.base.BaseService;
import yt.demo.appcommondb.vo.ConditionVO;
import yt.demo.appcoresystem.entity.*;
import yt.demo.appcoresystem.mapper.SystemRoleMapper;
import yt.demo.appcoresystem.mapper.SystemUserRoleMapper;
import yt.demo.appcoresystem.service.ISystemUserRoleService;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Slf4j
@Service
public class SystemUserRoleService extends BaseService<SystemUserRole, SystemUserRoleMapper> implements ISystemUserRoleService {

      SystemRoleMapper roleMapper;

    @Autowired
    public SystemUserRoleService(SystemUserRoleMapper mapper,SystemRoleMapper roleMapper) {
        super(mapper, SystemUserRole.class);
        this.roleMapper = roleMapper;
    }

    @Override
    protected List<ConditionVO<SystemUserRole, ?>> whereConditions(SystemUserRole params) {
        return List.of();
    }

    public void syncRole(Long userId, List<Long> roleIds) {

        List<SystemUserRole> userRoleList = userRoleList(List.of(userId));

        List<Long> currentIds = getRoleIds(userRoleList);

        List<Long> toDelete = currentIds.stream()
                .filter(roleId -> !roleIds.contains(roleId))
                .toList();

        // 计算出需要插入 ID
        List<Long> toInsert = roleIds.stream()
                .filter(roleId -> !currentIds.contains(roleId))
                .toList();

        // 删除需要删除的关联
        if (!toDelete.isEmpty()) {
            deleteUserRole(userId, toDelete);
        }
        // 批量插入新的关联
        if (!toInsert.isEmpty()) {
            List<SystemUserRole> userDepts = toInsert.stream()
                    .map(roleId -> {
                        SystemUserRole systemUserRole = new SystemUserRole();
                        systemUserRole.setUserId(userId);
                        systemUserRole.setRoleId(roleId);
                        return systemUserRole;
                    })
                    .toList();
            if (batchInsert(userDepts)) {
                throw new LogicException("同步失败");
            }
        }
    }

    public void deleteUserRole(Long userId, List<Long> userIds) {
        List<ConditionVO<SystemUserRole, ?>> conditions = new ArrayList<>();
        conditions.add(ConditionVO.createCondition(SystemUserRole::getUserId, "eq", userId));
        conditions.add(ConditionVO.createCondition(SystemUserRole::getRoleId, "in", userIds));
        deleteWhere(conditions);
    }

    public List<Long> getUserRoleIds(Long userId) {
        List<SystemUserRole> userRoleList = userRoleList(List.of(userId));
        return getRoleIds(userRoleList);
    }

//    public List<String> getUserRoleIdsRoutes(Long userId) {
//        List<Long> roleIds = getUserRoleIds(userId);
//        if (roleIds == null || roleIds.isEmpty()) {
//            return List.of();
//        }
//        if (roleIds.contains(1L)) {
//            return List.of("*");
//        }
//        return menuService.getRoleRoutes(roleIds);
//    }

    public void belongsToRole(List<Long> userIds, List<SystemUser> list) {
        if (userIds.isEmpty()) {
            return;
        }
        List<SystemUserRole> userRoleList = userRoleList(userIds);

        //根据 DeptId 查询所有角色
        List<Long> beIds = getRoleIds(userRoleList);
        if (beIds.isEmpty()) {
            return;
        }
        //批量查询所有角色
        List<SystemRole> beList = roleMapper.selectBatchIds(beIds);

        //创建一个映射用户ID到角色列表的映射
        Map<Long, List<SystemRole>> beMap = userRoleList.stream()
                .collect(Collectors.groupingBy(SystemUserRole::getUserId,
                        Collectors.mapping(userBe ->
                                        beList.stream().filter(be -> be.getId().equals(userBe.getRoleId()))
                                                .findFirst().orElse(null),
                                Collectors.toList())));
        // 填充用户的角色信息
        list.forEach(user -> {
            List<SystemRole> beLists = beMap.get(user.getId());
            if (beLists != null) {
                user.setRoleIds(beLists.stream().map(SystemRole::getId).collect(Collectors.toList()));
                user.setRoleName(beLists.stream().map(SystemRole::getName).collect(Collectors.joining(", ")));
            }
        });
    }

    private List<SystemUserRole> userRoleList(List<Long> userIds) {
        LambdaQueryWrapper<SystemUserRole> wrapper = new LambdaQueryWrapper<>();
        return mapper.selectList(
                wrapper.in(SystemUserRole::getUserId, userIds)
        );
    }

    private List<Long> getRoleIds(List<SystemUserRole> list) {
        return list.stream()
                .map(SystemUserRole::getRoleId)
                .distinct() // 去重
                .toList();
    }
}
